<?php
namespace App\Model;
use Core\Component\Di;

class GroupRelation{
    protected $db;
    protected $tableName = 'group_relation';

    function __construct(){
        $db = Di::getInstance()->get("MYSQL");
        if($db instanceof \MysqliDb){
            $this->db = $db;
        }
    }

    public function userIntoGroup($userId,$groupId){
        if(!$userId || !$groupId){
            return 0;
        }
        $data["user_id"] = $userId;
        $data["group_id"] = $groupId;
        $data['status'] = 1;
        $id = $this->db->insert($this->tableName,$data);
        if($id){
            return 0;
        }
        return $id;
    }

    public function userLeaveGroup($userId,$groupId){
        if(!$userId || !$groupId){
            return [];
        }
        $this->db->where("user_id", $userId);
        $this->db->where("group_id", $groupId);
        $data['status'] = -1;
        $id = $this->db->update($this->tableName,$data);
        if(!$id){
            return [];
        }
        return $id;
    }

    public function getGroupIdByUserId($userId){
        if(!$userId){
            return [];
        }
        $this->db->where("user_id", $userId);
        $this->db->where("status", 1);
        $column = 'group_id as groupId';
        $info = $this->db->get($this->tableName,NULL,$column);
        if(!$info){
            return [];
        }
        return array_column($info, 'groupId');
    }

    public function getUserIdByGroupId($groupId){
        if(!$groupId){
            return [];
        }
        $this->db->where("group_id", $groupId);
        $this->db->where("status", 1);
        $column = 'user_id as userId';
        $info = $this->db->get($this->tableName,NULL,$column);
        if(!$info){
            return [];
        }
        return array_column($info, 'userId');
    }
}
